#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>

typedef void (*func_t) ();

#define NUM 5
func_t handlers[NUM + 1];

//如下是各个功能函数
void Download()
{
	printf("我是一个下载任务...\n");
}
void Flush()
{
	printf("我是一个刷新任务...\n");
}
void Log()
{
	printf("我是一个记录日志的任务...\n");
}

//注册函数，将需要各种功能函数写入到上述函数指针数组中
void registerHandler(func_t h[], func_t f)
{
	int i = 0;
	for (; i < NUM; i++)
	{
		if (h[i] == NULL) break;

	}
	//指针数组满了
	if (i == NUM) return;
	h[i] = f;
	h[++i] = NULL;
}

int main()
{
	registerHandler(handlers, Download);
	registerHandler(handlers, Flush);
	registerHandler(handlers, Log);
	pid_t id = fork();
	if (id == 0)
	{
		while(1)
		{
			printf("我是子进程，pid: %d, ppid: %d\n", getpid(), getppid());
			sleep(3);
		}
		exit(10);
	}

	//父进程
	while(1)
	{
		int status = 0;
		pid_t rid = waitpid(id, &status, WNOHANG);
		if (rid > 0)
		{
			printf("wait success, rid: %d, exit code: %d, exit signal: %d\n", rid, (status>>8)&0xFF, status&0x7F);
			break;
		}
		else if (rid == 0)
		{
			//函数指针进行回调
			int i = 0;
			for (; handlers[i]; i++)
			{
				handlers[i]();
			}
			printf("本轮调用结束，子进程没有退出\n");
			sleep(1);
		}
		else
		{
			printf("等待失败\n");
			break;
		}
	}
	return 0;
}
